# -*- coding: utf-8 -*-
import datetime

from celery import task
from celery.schedules import crontab
from celery.task.base import periodic_task

from blueking.component.shortcuts import get_client_by_user
from uxsino.models import Host, MemDiskCpuHis
import base64

@task()
def query_status_and_getValue():
    client = get_client_by_user("admin");
    datas = MemDiskCpuHis.objects.filter(state = False);
    seqes = set([itm.seq for itm in datas]);
    # 检查每一个
    if seqes:
        for seq in seqes:
            """ 执行检查 """
            job = {"bk_biz_id": 2, "job_instance_id": seq}
            res = client.job.get_job_instance_status(job);
#             logger.error("***检查状态*****************************************")
#             logger.error(res);
#             logger.error("***检查状态 end*****************************************")
            if res and res.get("result"):
                data = res.get("data");
                if data and data.get("is_finished"): #作业已经完成
#                     logger.error("***执行日志获取*****************************************")
                    log = client.job.get_job_instance_log(job);
#                     logger.error(log);
#                     logger.error("***执行日志获取end*****************************************")
                    if log and log.get("result"): #保存日志内容
                        logData = log.get("data");
                        if logData:
                            for logDataItm in logData:
                                if logDataItm.get("is_finished"):
                                    steps = logDataItm.get("step_results");
                                    if steps:
                                        for s in steps:
                                            logs = s.get("ip_logs");
                                            if logs:
                                                for lg in logs:
                                                    ip = lg.get("ip");
                                                    ##start_time = lg.get("start_time");
                                                    log_content = lg.get("log_content");
                                                    ##total_time = lg.get("total_time");
                                                    log_time = ""; 
                                                    mem = disk = cpu = 0;
                                                    if log_content:
                                                        cnt = log_content.split("|");
                                                        if len(cnt) == 4:
                                                            log_time = cnt[0];
                                                            mem = cnt[1];
                                                            disk = cnt[2];
                                                            cpu = cnt[3];
                                                        
                                                    
                                                    host = Host.objects.filter(ip=ip);
                                                    if host:
                                                        h = host[0];
                                                        h.disk_use = disk;
                                                        h.cpu_use = cpu;
                                                        h.mem_use = mem;
                                                        h.update_time = datetime.datetime.now();
                                                        h.save();
                                                        rec = MemDiskCpuHis.objects.filter(seq=seq, host = h);
                                                        if rec:
                                                            r = rec[0];
                                                            r.mem_use = mem;
                                                            r.disk_use = disk;
                                                            r.cpu_use = cpu;
                                                            r.update_time = datetime.datetime.now();
                                                            r.log_time = log_time;
                                                            r.state = True;
                                                            r.save();
    return;                                                 


@task()
def execute_script(hosts):
    client = get_client_by_user("admin");
    script = "#!/bin/bash \n" +"MEMORY=$(free -m | awk 'NR==2{printf \"%.2f%%\", $3*100/$2 }')\n" +"DISK=$(df -h | awk '$NF==\"/\"{printf \"%s\", $5}')\n" +"CPU=$(top -bn1 | grep load | awk '{printf \"%.2f%%\", $(NF-2)}')\n" +"DATE=$(date \"+%Y-%m-%d %H:%M:%S\")\n" +"echo -e \"$DATE|$MEMORY|$DISK|$CPU\" \n";
    if not hosts:
        hosts = Host.objects.all();
    ip_list = [{"ip": h.get("ip"), "bk_cloud_id": 0} for h in hosts.values()];
    params = {
        "bk_biz_id": 2,
        "script_content": base64.b64encode(script),
        "script_type": 1,
        "account": "root",
        "ip_list": ip_list
    };
#     logger.error("***开始执行脚本*****************************************")
    res = client.job.fast_execute_script(params);
#     logger.error(res);
#     logger.error("***返回结果end*****************************************")
    
    if res.get("result"): #执行成功
        data = res.get("data");
        if data:
            ins_id = data.get("job_instance_id");
            if ins_id:
                for h in hosts:
                    rec = MemDiskCpuHis();
                    rec.host = h;
                    rec.seq = ins_id;
                    rec.state = False;
                    rec.cpu_use = 0;
                    rec.disk_use = 0;
                    rec.mem_use = 0;
                    rec.job_time = datetime.datetime.now();
                    rec.update_time = datetime.datetime.now();
                    rec.save();
    return;
""" 执行脚本的计划任务 """
@periodic_task(run_every=crontab(minute='*/1', hour='*', day_of_week="*"))
def exec_job():
    now = datetime.datetime.now();
#     logger.info("同步主机数据任务启动，将在60s后执行，当前时间：{}".format(now))
    execute_script.apply_async(args=[[]], eta=now + datetime.timedelta(seconds=60));
    return;

""" 执行脚本的计划任务 """
@periodic_task(run_every=crontab(minute='*/1', hour='*', day_of_week="*"))
def check_job():
    now = datetime.datetime.now();
#     logger.info("同步主机数据任务启动，将在60s后执行，当前时间：{}".format(now))
    query_status_and_getValue.apply_async(args=[], eta=now + datetime.timedelta(seconds=2));
    return;



